package com.mall.seckill_mall.config;

import com.mall.seckill_mall.common.RabbitConstants;
import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.DirectExchange;
import org.springframework.amqp.core.Queue;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

@Configuration
public class RabbitMQConfig {

    @Bean
    public Queue seckillQueue() {
        return new Queue(RabbitConstants.SEKILL_QUEUE, true);
    }

    /*
     * 声明死信队列
     */
    @Bean
    public Queue dlxQueue() {
        return new Queue(RabbitConstants.DLX_QUEUE, true);
    }

    /*
     * 声明订单队列
     */
    @Bean
    public Queue orderQueue() {
        /* 1. 设置订单队列参数  */
        Map<String, Object> params = new HashMap<>();
        //声明消息过期后，发往的死信队列交换机名称
        params.put("x-dead-letter-exchange", RabbitConstants.DLX_EXCHANGE);
        //声明消息过期后，发往的死信队列的路由键
        params.put("x-dead-letter-routing-key", RabbitConstants.DLX_ROUTING_KEY);
        return new Queue(RabbitConstants.ORDER_QUEUE, true, false, false, params);
    }

    /*
     * 声明订单交换机
     */
    @Bean
    public DirectExchange orderExchange() {
        return new DirectExchange(RabbitConstants.ORDER_EXCHANGE, true, false);
    }

    /*
     * 声明死信交换机
     */
    @Bean
    public DirectExchange dlxExchange() {
        return new DirectExchange(RabbitConstants.DLX_EXCHANGE, true, false);
    }

    @Bean
    public DirectExchange seckillExchange() {
        return new DirectExchange(RabbitConstants.SEKILL_EXCHANGE, true, false);
    }

    /*
     * 绑定订单队列与订单交换机
     */
    @Bean
    public Binding orderBinding() {
        return BindingBuilder.bind(orderQueue()).to(orderExchange()).with(RabbitConstants.ORDER_ROUTING_KEY);
    }

    /*
     * 绑定死信队列和死信交换机
     */
    @Bean
    public Binding dlxBinding() {
        return BindingBuilder.bind(dlxQueue()).to(dlxExchange()).with(RabbitConstants.DLX_ROUTING_KEY);
    }

    @Bean
    public Binding seckillBinding() {
        return BindingBuilder.bind(seckillQueue()).to(seckillExchange()).with(RabbitConstants.SEKILL_ROUTING_KEY);
    }

//    @Bean
//    public Queue testQueue() {
//        return new Queue("test_queue", true);
//    }
//
//    @Bean
//    public DirectExchange testEx() {
//        return new DirectExchange("test_ex", true, false);
//    }
//
//    @Bean
//    public Binding testBind() {
//        return BindingBuilder.bind(testQueue()).to(testEx()).with("test");
//    }
}
